<template>
  <div>
    <!--还款码  -->
    <div style="padding: 15px">
      <el-button type="primary" v-show="permiss['/approveDetails/echoVirtualCard']"
                 @click="clickVirtualCard">
        {{ $t('生成虚拟卡') }} (VA)
      </el-button>
    </div>
    <Table :table-column="tableColumn" :table-data="data" :page="false" border
           max-height="300px"
           :header-style="{backgroundColor:'#fffbed'}">
      <template slot="handle" slot-scope="{row}">
        <el-button v-show="permiss['/approveDetails/cancelVirtualAccount']" type="text" @click="cancelVirtualAccount(row)">{{ $t('取消虚拟卡') }}</el-button>
      </template>
    </Table>
    <Dialog :title="$t('生成虚拟卡')" :visible.sync="visible" @cancel="visible = false"
            :footer="permiss['/approveDetails/registerVirtualAccount']"
            @close="clearForm" @confirm="repaymentSubmit" :confirm-loading="laoding">
      <el-form label-width="100px" :model="form" ref="form">
        <el-form-item :label="$t('虚拟卡用途')" prop="payType" :rules="[
               {required: true, message: this.$t('请选择'),trigger:'change'},
        ]">
          <el-select v-model="form.payType" @change="payTypeChange">
            <el-option :value="1" :label="$t('还款')"></el-option>
            <el-option :value="2" :label="$t('展期')"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('展期天数')" v-if="form.payType === 2" prop="rollDay" :rules="[
               {required: true, message: this.$t('请选择'),trigger:'change'},
        ]">
          <el-select v-model="form.rollDay" @change="changeRollDay">
            <el-option v-for="item in rollDaySelect" :key="item" :value="item" :label="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('支付方式')" prop="vaType" v-if="isMxg" :rules="[
               {required: true, message: this.$t('请选择'),trigger:'change'},
        ]">
          <el-select v-model="form.vaType">
            <el-option :value="0" label="STP"></el-option>
            <el-option :value="1" label="OXXO"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('订单号')">
          <div style="line-height: 32px">
            {{ routesQuery.orderId }}
          </div>
        </el-form-item>
        <el-form-item :label=" form.rollDay ? $t('展期金额') : $t('还款金额')">
          <div style="line-height: 32px">
            {{ form.amount }}
          </div>
        </el-form-item>
        <el-form-item v-if="!isMxg" :label="$t('支付方式')">
          <div style="line-height: 32px">
            {{ form.name }}
          </div>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
// import qs from "qs";
import {queryVirtualAccount,echoVirtualCard,registerVirtualAccount,cancelVirtualAccount} from '@/api/order'
import {selectRollOver} from '@/api/product'
export default {
  name: "repaymentCode",
  props: ['childPermiss','routesQuery'],
  data() {
    return {
      data: [],
      tableColumn: [
        {label: this.$t('虚拟卡用途'), align: 'center', prop: 'payType', minWidth: 120},
        {label: this.$t('银行账号'), align: 'center', prop: 'accNo',},
        {label: this.$t('银行卡账户名称'), align: 'center', prop: 'accName', minWidth: 150},
        {label: this.$t('银行名称'), align: 'center', prop: 'bankName',},
        {label: this.$t('支行名称'), align: 'center', prop: 'bankBranch',},
        {label: this.$t('创建时间'), align: 'center', prop: 'creationTime', minWidth: 150},
        {label: this.$t('操作人'), align: 'center', prop: 'inputName',},
        {label: this.$t('操作'), align: 'center', slot: 'handle'},
      ],
      visible: false,
      form: {},
      permiss: {},
      rollDaySelect: [],
      laoding: false
    }
  },
  computed: {
    isMxg() {
      return process.env.VUE_APP_REGION === 'moxige'
    }
  },
  created() {
    const obj = {}
    if (this.childPermiss && this.childPermiss.length !== 0) {
      for (let i = 0; i < this.childPermiss.length; i++) {
        obj[this.childPermiss[i].url] = this.childPermiss[i].url
      }
      this.permiss = obj
    }
    this.getList()
  },
  methods: {
    async getList() {
      const {orderId} = this.routesQuery
      const res = await queryVirtualAccount({
        loanRecordId: orderId
      })
      if (res.code === 1 && res.data) {
        this.data = [res.data].map(item => {
          item.payType = item.payType === 1 ? this.$t('还款') : this.$t('展期')
          return item
        })
      } else {
        this.data = []
      }
    },
    clickVirtualCard() {
      // 默认还款
      this.form.payType = 1
      this.createRepaymentCode()
    },
    // 生成虚拟卡
    async createRepaymentCode() {
      const {orderId} = this.routesQuery
      const {rollOverDay, payType, rollDay, vaType} = this.form
      const res = await echoVirtualCard({
        loanRecordId: orderId,
        rollOverDay: rollDay,
        payType
      })
      if (res.code === 1) {
        this.visible = true
        // const isRollDay = dayjs(res.data.refundDate).format('YYYY-MM-DD') === dayjs(new Date()).format('YYYY-MM-DD')
        this.form = {
          ...res.data,
          // isRollDay,
          payType,
          rollOverDay,
          rollDay,
          vaType
        }
      }
    },
    // 展期天数切换
    changeRollDay() {
      this.form.payType = 2
      this.createRepaymentCode()
    },
    // 获取天数
    async getRollDay() {
      const {productName} = this.routesQuery
      const res = await selectRollOver({
        productName: productName
      })
      if (res.code === 1) {
        this.rollDaySelect = res.data.map(item => item.rollOverDay)
      }
      // const ares = await this.$get('loanProduct/selectRollOver', {
      //   productName: params.productName
      // })
      // console.log(ares)
    },
    // 切换还款类型
    payTypeChange(value) {
      if (value === 2) {
        this.getRollDay()
      } else {
        this.rollDaySelect = []
        this.form.rollDay = null
        this.createRepaymentCode()
      }
    },
    //  还款码提交
    repaymentSubmit() {
      this.$refs.form.validate(async v => {
        if (v) {
          this.laoding = true
          const {orderId, userId} = this.routesQuery
          const {vaType, payType, rollDay} = this.form
          const res = await registerVirtualAccount({
            loanRecordId: orderId,
            userId: userId,
            rollDay,
            vaType, payType
          })
          if (res.code === 1) {
            this.$message.success(this.$t('操作成功'))
            this.visible = false
            this.laoding = false
            this.getList()
          } else {
            this.laoding = false
          }
        }
      })
    },
    async cancelVirtualAccount({id}) {
      this.$confirm(this.$t("为避免造成损失，请确认是否进行该操作") + '?', this.$t("提示"), {
        type: "warning",
      }).then(async () => {
        const res = await cancelVirtualAccount({id})
        if (res.code === 1) {
          this.$message.success(this.$t('操作成功'))
          this.getList()
        }
      }).catch(() => {
      });

    },
    clearForm() {
      this.$refs.form.resetFields()
      this.form = {}
    }
  }
}
</script>

<style scoped>

</style>
